package org.grow.leavejpa.config;


import org.grow.leavejpa.entity.UserInfo;
import org.grow.leavejpa.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-6-7
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthHandler authHandler;
    @Autowired
    private EntryPointHandler entryPointHandler;
    @Autowired
    private PermissionDataSource permissionDataSource;
    @Autowired
    private NormalDecisionManager normalDecisionManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//
        http.httpBasic().disable();
        http.cors().disable();
        http.csrf().disable();
//        http.formLogin();

        UserInfo userInfo = new UserInfo();
        userInfo.setNickname("匿名访问者");
        userInfo.setUsername("anonymous007");
        userInfo.setIsEnable(true);
        userInfo.setPassword("121212");
        userInfo.setLastLoginTime(LocalDateTime.now());
        http.anonymous().principal(userInfo);

        http.formLogin()
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(authHandler)
                .failureHandler(authHandler).permitAll();
        http.logout()
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        System.out.println("用户注销中");
                        httpServletResponse.setStatus(200);
                        UserInfo principal = (UserInfo) authentication.getPrincipal();
                        httpServletResponse.getWriter().println(principal.getNickname()+" good bye ");
                    }
                });

//        有身份
//       1， 真身份证 用户名密码  2，假身份证 匿名登录 3 不带任何身份证
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
//                      第二 ，根据url查询roles
                        o.setSecurityMetadataSource(permissionDataSource);
//                       第三 ，根据第一第二两个roles取交集判定是否有权限
                        o.setAccessDecisionManager(normalDecisionManager);
                        return o;
                    }
                });

        http.authorizeRequests().antMatchers("/**").permitAll();
        http.exceptionHandling()
                .authenticationEntryPoint(entryPointHandler)
                .accessDeniedHandler((httpServletRequest, httpServletResponse, e) -> {
//       第四步  如果没权限 告诉前端
                    System.out.println("权限拦截已经触发");
                    httpServletResponse.setStatus(930);
                    String name = SecurityContextHolder.getContext().getAuthentication().getName();
                    String msg = name+"没有权限访问"+httpServletRequest.getRequestURI()+" == "+e.getMessage();
                    httpServletResponse.getWriter().println(msg);
                    httpServletResponse.flushBuffer();

                });
    }
// System.out.println("实在没有通行证，没有临时正没有正常通行证");
//                        httpServletResponse.setStatus(990);
//                        httpServletResponse.getWriter().println("没有任何通行证"+e.getMessage());
//                        httpServletResponse.flushBuffer();
    @Autowired
    private UserInfoService userInfoService;
    @Override
    protected UserDetailsService userDetailsService() {
        return userInfoService;
    }

}
